
jQuery(document).ready(function($)
{
    container = $('#zotop-container');
    container.isotope({
        itemSelector: '.element',
        itemPositionDataEnabled: true,
        layoutMode: 'cellsByRow',
        cellsByRow: {
            columnWidth: 200,
            rowHeight: 200
        }
    });

    var btn = $('.btn-primary');
    btn.click(function() {
        container.isotope('shuffle', afterShuffle);
        return false;
    });

    $('.element').click(function() {
        majPerson(this);
    });

    setBackgrounds();
});

function afterShuffle() {
    console.log('afterShuffle');

    var thechoosenone = null;
    var lastpos = 1000;

    $('.element').each(function() {
        var position = $(this).data('isotope-item-position');
        if (position.x < lastpos) {
            lastpos = position.x;
            thechoosenone = this;
        }
    });

    majPerson(thechoosenone);
}


function majPerson(person) {


    $(person).addClass('large');
    $('.element').not('.large').addClass('nope');
    container.isotope('reLayout');

    var who = $.trim($('.symbol', person).text());

    var nb = $('.weight', person);

    var nbnow = parseInt(nb.text()) + 1;
    nb.html(nbnow);

    var data = {who: who, nb: nbnow};

    $.ajax({
        url: "",
        type: "post",
        data: data,
        dataType: "json"
    });
}


function setBackgrounds() {

    container.isotope('reLayout');

    var value = parseInt((Math.random() * 15)) + 1;
    if (value < 10)
        value = '0' + value;

    $.vegas({
        src: 'img/back.jpg'
    })('overlay', {
        src: 'img/overlays/' + value + '.png'
    });

    container.isotope('reLayout');
}